package com.zhongzhi.thread;

import java.awt.List;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import com.zhongzhi.common.Common;
import com.zhongzhi.common.Plc;
import com.zhongzhi.common.Primary;
import com.zhongzhi.springboot.pojo.Equipment;
import com.zhongzhi.springboot.pojo.EquipmentShow;

import lombok.extern.log4j.Log4j;

/**
 * plc通信守护线程
 * @author Administrator
 *
 */
@Log4j
public class PlcGuardThread extends Thread{

	ArrayList<Equipment> list=null;			//plc信息
	Set<Thread> keySet = null;				//线程对象
	Set<String> set=null;					//线程名称
	ArrayList<String> ipList=null;			//计算机ip地址集合
	/**
	 * 此线程的作用就是开通plctx线程,并且如果检测到新的plc则开启新的plc线程
	 */
	@Override
	public void run() {
		/**
		 * 1:获取公共资源
		 * 2:循环获取本机ip
		 * 3:检查得到的plc信息,如果本机ip与plc运行ip是否
		 * 4:如果一致,则需要检查这个plc的线程是否存在,如果不存在,则创建这个plc的线程
		 */
		log.info("启动plc通信守护线程");
		
		//循环次数,获取plc的等数据的时间
		int num=0;
		while (true) {
			//1:获取公共资源
			/**获取所有线程的对象*/
			keySet = Thread.getAllStackTraces().keySet();
			/**获取所有线程的名字*/
			set = new HashSet<String>();
			for (Thread thread : keySet) {
				String name = thread.getName();
				set.add(name);
			}
				HashMap<Integer, EquipmentShow> equipmentMap = Common.getEquipmentMap();
				Set<Integer> keySet2 = equipmentMap.keySet();
				
				for (Integer integer : keySet2) {
					EquipmentShow equipment = equipmentMap.get(integer);
					String plcName = equipment.getPlcName() + ": " +equipment.getId();
					boolean contains = set.contains(plcName);
					if (contains==false) {
						PlcThread plcThread = new PlcThread(equipment);
						plcThread.setName(plcName);
						plcThread.start();
						Common.getPlcThread().put(equipment.getId(), plcThread);
						log.info("plc通信线程:"+plcName+"创建");
					}
				}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			num++;
			if (num==20) {
				num=0;
			}
		}

	}
}
